$(document).ready(init);

var adminRoles;
var adminPrivilege;
var adminInfo;
var funItems;

function init(){

	initData();
	renderPage();
	bindEvent();
	
}

function initData(){
	adminInfo = responseVO.objects.adminInfo;
	adminRoles = responseVO.objects.roles;
	adminPrivilege = responseVO.objects.privileges;
	funItems = responseVO.objects.funItems;
	
}

function renderPage(){
	
	renderFunctionMenu();
	$('#welcomLb').text(adminInfo.loginName);
	$('#logoutLink').attr('href',webappName+'/admin/logout');
}

function bindEvent(){

	$('.funItemLink').click(onFunItemClicked);
	$(document).bind(_EVENT_LOAD_COMPONENT,loadComponent);
	
}

function renderFunctionMenu(){
	
	$('#functionMenuDiv').empty();
	$('#functionMenuDiv').append("<div id='functionMenu' class='easyui-accordion' fit='true' border='false'></div>")
	renderFunctionCatalog();
	renderFunItem2Catalog();
	$('#functionMenu').accordion();
}

function renderFunctionCatalog(){
	var catalogHtml = "";
	var funItem;
	
	for(var i=0;i<funItems.length;i++){
		funItem = funItems[i];
		if ($(getRenderedFunctionCatalog(funItem)).length==0){
			catalogHtml = "<div icon='icon-add' title='"+funItem.catalogTitle+"'   style='padding:10px;'></div>";
			$('#functionMenu').append(catalogHtml);
		}
	}
}


function renderFunItem2Catalog(){
	var itemHtml="";
	for(var i=0;i<funItems.length;i++){
		funItem = funItems[i];
		itemHtml = "<a href='javascript:void(0)' class='funItemLink'  code='"+funItem.code+"' component='"+funItem.component+"' >"+funItem.title+"</a></p>"
		$(getRenderedFunctionCatalog(funItem)).append(itemHtml);
	}
	
}

function getRenderedFunctionCatalog(funItem){
	var catalogElement =  $("#functionMenu > div[title="+funItem.catalogTitle+"]");
	return catalogElement;
}


function onFunItemClicked(event){
	$(event.target).trigger(_EVENT_LOAD_COMPONENT,$(event.target).attr('component'));
}



function loadComponent(event,data){
	var componentId = data;
	var componentUri = webappName+_BASE_COMPONENT_URI+componentId;
	var componentTitle = $(event.target).text();
	var content = '<iframe scrolling="no" frameborder="0"  src="'+componentUri+'" style="width:100%;height:100%;"></iframe>';  
	
	if ($('#mainContentDiv').tabs('exists',componentTitle)){
		$('#mainContentDiv').tabs('select', componentTitle); 
	}else{
		$('#mainContentDiv').tabs('add',{
			title:componentTitle,
			content:content,
			closable:true
		});
	}
	
}

